#include "zf_host.h"
#include <string.h> 

// ================== 1. 协议定义 ==================

// 帧头 (如果波形出不来，请把 0xAA 改成 0xA5 试试)
#define SEND_HEAD     0xAA 
#define REC_HEAD      0x55  
#define FUNC_SCOPE    0x10  

#pragma pack(1) 
typedef struct
{
    uint8_t head;           
    uint8_t channel_num;    
    uint8_t check_sum;      
    uint8_t length;         
    float   data[8];        
} zf_scope_struct;
#pragma pack()

static float *param_registry[8] = {0}; 
static zf_scope_struct tx_packet; 

// ================== 2. 内部工具函数 ==================

static uint8_t Calculate_Sum(uint8_t *buffer, uint32_t len)
{
    uint8_t sum = 0;
    while(len--) sum += *buffer++;
    return sum;
}

// ================== 3. 发送示波器 ==================
static void Send_Scope(float *data, uint8_t count)
{
    uint8_t total_len;
    if(count > 8) count = 8;

    tx_packet.head = SEND_HEAD; 
    tx_packet.channel_num = (count & 0x0F) | FUNC_SCOPE;
    total_len = 4 + (count * 4);
    tx_packet.length = total_len;
    memcpy(tx_packet.data, data, count * sizeof(float));
    
    tx_packet.check_sum = 0;
    tx_packet.check_sum = Calculate_Sum((uint8_t*)&tx_packet, total_len);

    uart_write_buffer(HOST_UART, (uint8_t*)&tx_packet, total_len);
}

// ================== 4. 接收调参指令 (修复编译错误版) ==================
static void Check_Command(void)
{
    uint8_t tmp;
    uint8_t buf[8];
    uint8_t sum_cal;
    float val;

    // 【核心修改】使用 uart_query_byte 代替 uart_query + uart_read_byte
    // 这个函数会检查是否有数据，如果有，直接读到 tmp 里并返回 1
    if(uart_query_byte(HOST_UART, &tmp)) 
    {
        // 匹配帧头
        if(tmp == REC_HEAD) 
        {
            // 接收剩余7个字节
            for(int i=0; i<7; i++) {
                int t = 5000000; 
                // 循环查询直到读取成功
                while(!uart_query_byte(HOST_UART, &buf[i]) && t--);
                if(t<=0) return; // 超时退出
            }

            // 校验
            sum_cal = REC_HEAD + buf[0] + buf[1] + buf[3] + buf[4] + buf[5] + buf[6];
            
            if(sum_cal == buf[2]) 
            {
                uint8_t ch = buf[1];
                if(ch >= 1 && ch <= 8 && param_registry[ch - 1] != 0) {
                    val = *(float*)(&buf[3]);
                    *(param_registry[ch - 1]) = val;
                }
            }
        }
    }
}

// ==================== 5. 对外接口 ====================

void ZF_Host_Init(void)
{
    uart_init(HOST_UART, HOST_BAUD, HOST_TX_PIN, HOST_RX_PIN);
    memset(param_registry, 0, sizeof(param_registry));
}

void ZF_Host_Register(uint8_t Channel, float *Ptr)
{
    if(Channel >= 1 && Channel <= 8) param_registry[Channel - 1] = Ptr;
}

void ZF_Host_Task(float ch1, float ch2, float ch3, float ch4)
{
    Check_Command();

    static uint8_t div = 0;
    if(++div % 5 == 0) 
    {
        float data[4] = {ch1, ch2, ch3, ch4};
        Send_Scope(data, 4);
    }
}